package se.olli.jonsered;

import java.util.ArrayList;
import java.util.Random;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.TableLayout;
import android.widget.TableRow;

public class MemoryActivity extends Activity implements OnClickListener {
	private Handler mHandler = new Handler();
	private AlertDialog.Builder builder;
	private AlertDialog alert;
	private ArrayList<Integer> imgArray = new ArrayList<Integer>();	//Randomized list
	private final Integer[] images = {		// Array of images
			R.drawable.mem_katt, R.drawable.mem_kb, R.drawable.mem_nalle, 
			R.drawable.mem_te, R.drawable.mem_ved, R.drawable.mem_rat,
			R.drawable.mem_katt, R.drawable.mem_kb, R.drawable.mem_nalle, 
			R.drawable.mem_te, R.drawable.mem_ved, R.drawable.mem_rat,
	};
	private boolean[] validPos;
	private final int rows = 4, cols = 3;
	private int firstPick = -1, secondPick = -1, firstPos = -1, cardsLeft = images.length,
			defaultImg = R.drawable.memory_back, numOfCards = images.length;
	private boolean free = true;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.memory_layout);
		
		builder = new AlertDialog.Builder(this);
		builder.setMessage("Grattis!\nVill du spela igen?")
				.setCancelable(false)
				.setPositiveButton("Ja", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						Intent intent = getIntent();
						finish();
						startActivity(intent);
					}
				})
				.setNegativeButton("Nej", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						finish();
					}
				});
		
		alert = builder.create();
		
		setUpGame();

	}
	
	private void setUpGame() {
		randomizeList();
		validPos = new boolean[numOfCards];
		for (int i = 0; i < numOfCards; i++)
			validPos[i] = true;
		setUpGui();
	}

	private void randomizeList() {
		ArrayList<Integer> tmp = new ArrayList<Integer>();
		for (int i = 0; i < images.length; i++)
			tmp.add(images[i]);
		Random rand = new Random();
		for (int i = tmp.size(); i > 0; i--) {
			int random = rand.nextInt(i);
			imgArray.add(tmp.remove(random));
		}
	}
	
	private void setUpGui() {
		Display display = getWindowManager().getDefaultDisplay(); 
		int maxWidth = (display.getWidth() / 3) - 10;
		int maxHeight = display.getHeight() / 6;
		int maxSize = maxWidth;
		if(maxWidth > maxHeight)
			maxSize = maxHeight;
		TableLayout table = (TableLayout) findViewById(R.id.table);
		LayoutParams tRow = (new TableRow.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
		int id = 0;
		for (int i = 0; i < rows; i++) {
			TableRow row = new TableRow(this);
			row.setLayoutParams(tRow);
			row.setGravity(Gravity.CENTER);
			for (int j = 0; j < cols; j++) {
				ImageView img1 = new ImageView(this);
				img1.setImageResource(defaultImg);
				img1.setId(id);
				img1.setOnClickListener(this);
				img1.setAdjustViewBounds(true);
				img1.setMaxHeight(maxSize);
				img1.setMaxWidth(maxSize);
				img1.setPadding(7, 7, 7, 7);
				row.addView(img1);
				id++;
			}
			table.addView(row);
		}
	}

	public void onClick(View v) {
		final int index = v.getId();
		if(free && validPos[index]) {
			final ImageView imView = (ImageView) v;
			if(firstPos < 0) {		// No card has been picked
				firstPick = imgArray.get(index);
				imView.setImageResource(firstPick);
				firstPos = index;
			} else if (firstPos != index) {		// Second pick
				secondPick = imgArray.get(index);
				imView.setImageResource(secondPick);
				free = false;
				mHandler.postDelayed(new Runnable() {
					public void run() {
						ImageView firstView = (ImageView) findViewById(firstPos);
						if(secondPick != firstPick) {
							firstView.setImageResource(defaultImg);
							imView.setImageResource(defaultImg);
						} else {
							firstView.setImageResource(R.drawable.invis);
							imView.setImageResource(R.drawable.invis);
							validPos[firstPos] = false;
							validPos[index] = false;
							cardsLeft -= 2;
							if(cardsLeft == 0) {
								alert.show();
							}
						}
						firstPos = -1;
						free = true;
					}
				}, 500);
				
			}
		}
	}
	/*
	private AnimationDrawable getAnimation(int image) {
		AnimationDrawable anim  = new AnimationDrawable();
		Drawable back = (Drawable)this.getResources().getDrawable(R.drawable.memory_back);
		Drawable front = (Drawable)this.getResources().getDrawable(image);
		anim.addFrame(back, 100);
		anim.addFrame(front, 100);
		return anim;
	}*/
}
